package models

import (
	"github.com/beego/beego/v2/client/orm"
)

// BookingSetting 预约配置模型
type BookingSetting struct {
	BaseModel
	StoreId             int64 `orm:"column(store_id)" json:"store_id"`          // 门店ID
	OrderLimit          int   `orm:"default(0)" json:"order_limit"`             // 用户每日最多可预约订单数，0为不限制
	LateCancelMinutes   int   `orm:"default(15)" json:"late_cancel_minutes"`    // 迟到多少分钟后系统自动取消订单
	AllowSelfCancel     bool  `orm:"default(true)" json:"allow_self_cancel"`    // 是否允许用户自助取消订单
	CancelBeforeMinutes int   `orm:"default(30)" json:"cancel_before_minutes"`  // 用户可在预约开始前多少分钟取消订单
	AllowEarlyCheckIn   bool  `orm:"default(true)" json:"allow_early_check_in"` // 是否允许用户提前开门
	EarlyCheckInMinutes int   `orm:"default(15)" json:"early_check_in_minutes"` // 用户可提前多少分钟开门
	TimeSlotInterval    int   `orm:"default(30)" json:"time_slot_interval"`     // 时间间隔，个性化设置，单位分钟
	MinBookingDuration  int   `orm:"default(60)" json:"min_booking_duration"`   // 最小计费单位，单位分钟
	MinBookingHours     int   `orm:"default(1)" json:"min_booking_hours"`       // 起约时长，单位小时
	MaxExtendMinutes    int   `orm:"default(60)" json:"max_extend_minutes"`     // 最小延长时长，单位分钟
	MaxChangeLocation   int   `orm:"default(1)" json:"max_change_location"`     // 单个订单最多可更换位置次数
	AllowModifyOrder    bool  `orm:"default(true)" json:"allow_modify_order"`   // 是否允许改签订单
	ModifyOrderMinutes  int   `orm:"default(30)" json:"modify_order_minutes"`   // 订单开始前多少分钟不允许改签
	MaxModifyOrderCount int   `orm:"default(1)" json:"max_modify_order_count"`  // 单个订单最多可改签次数
	AllowEarlyLeave     bool  `orm:"default(true)" json:"allow_early_leave"`    // 是否允许提前离店
	AllowPreBooking     bool  `orm:"default(true)" json:"allow_pre_booking"`    // 是否可提前预约
	PreBookingDays      int   `orm:"default(7)" json:"pre_booking_days"`        // 可提前预约天数
}

// TableName 设置表名
func (bs *BookingSetting) TableName() string {
	return "ss_booking_setting"
}

// GetBookingSettingByStoreId 根据门店ID获取预约配置
func GetBookingSettingByStoreId(storeId int64) (*BookingSetting, error) {
	o := orm.NewOrm()
	setting := &BookingSetting{StoreId: storeId}
	err := o.Read(setting, "StoreId")
	if err == orm.ErrNoRows {
		// 如果没有找到特定门店的配置，可以返回一个默认配置
		return &BookingSetting{
			StoreId:             storeId,
			OrderLimit:          0,
			LateCancelMinutes:   15,
			AllowSelfCancel:     true,
			CancelBeforeMinutes: 30,
			AllowEarlyCheckIn:   true,
			EarlyCheckInMinutes: 15,
			TimeSlotInterval:    30,
			MinBookingDuration:  60,
			MinBookingHours:     1,
			MaxExtendMinutes:    60,
			MaxChangeLocation:   1,
			AllowModifyOrder:    true,
			ModifyOrderMinutes:  30,
			MaxModifyOrderCount: 1,
			AllowEarlyLeave:     true,
			AllowPreBooking:     true,
			PreBookingDays:      7,
		}, nil
	}
	return setting, err
}

// GetAllBookingSettings 获取所有预约配置
func GetAllBookingSettings() ([]BookingSetting, error) {
	o := orm.NewOrm()
	var settings []BookingSetting
	_, err := o.QueryTable(new(BookingSetting)).All(&settings)
	return settings, err
}

// GetBookingSettingsByFranchiseId 根据加盟商ID获取预约配置列表
func GetBookingSettingsByFranchiseId(franchiseId int64) ([]BookingSetting, error) {
	o := orm.NewOrm()
	var settings []BookingSetting
	// First, get all stores for the franchise
	var stores []Store
	_, err := o.QueryTable(new(Store)).Filter("franchise_id", franchiseId).All(&stores)
	if err != nil {
		return nil, err
	}

	if len(stores) == 0 {
		return settings, nil // No stores, so no settings
	}

	// Get the store IDs
	var storeIDs []int64
	for _, store := range stores {
		storeIDs = append(storeIDs, store.Id)
	}

	// Get all booking settings for those store IDs
	_, err = o.QueryTable(new(BookingSetting)).Filter("store_id__in", storeIDs).All(&settings)
	return settings, err
}

// CreateOrUpdateBookingSetting 创建或更新预约配置
func CreateOrUpdateBookingSetting(setting *BookingSetting) (int64, error) {
	o := orm.NewOrm()
	exist := &BookingSetting{StoreId: setting.StoreId}
	err := o.Read(exist, "StoreId")
	if err == nil {
		setting.Id = exist.Id
		_, err = o.Update(setting)
		return setting.Id, err
	} else if err == orm.ErrNoRows {
		id, err := o.Insert(setting)
		return id, err
	}
	return 0, err
}

// DeleteBookingSetting 删除预约配置
func DeleteBookingSetting(id int64) error {
	o := orm.NewOrm()
	_, err := o.QueryTable(new(BookingSetting)).Filter("id", id).Delete()
	return err
}
